<?php
defined('EXEC') or die();
$transacao = 'forma_pagamento';

if(!$auth->isRead($transacao)){
	Util::info(Config::AUTH_MESSAGE);
	return true;
}
//Importando a classes
Loader::import('com.atitudeweb.SQL');
$form 			= false;
$rowEdit 		= array();
$table 			= ' tethys.tb_forma_pagamento ';
$tableEdit      = ' tethys.tb_forma_pagamento p left join tethys.tb_prazo_pagamento pz on p.ci_forma_pagamento=pz.cd_forma_pagamento ';
$tablepk 		= 'ci_forma_pagamento';
$limitPagina 	= 10; //Registros por p�gina
$faixa 			= 10; //Faixa de p�ginas que ir�o ser mostradas pagina��o (google)
$dif 			= 5; //A diferen�a que a faixa de p�ginas ir�o come�ar a caminhar (google)
$p 				= (@$_GET['p'] ? $_GET['p'] : 1);

//Exclus�o de v�rios ou um registro
if(isset($_POST['checkdel'])){
	if($auth->isDelete($transacao)){
		/*if(SQL::remove($table, $tablepk, $_POST['checkdel'])){
			Util::notice('Forma de Pagamento', 'Excluída com sucesso!');
			}
			else{*/
		Util::notice('Forma de Pagamento', 'Não é possivel apagar o registro pois o mesmo já foi utilizado !', 'error');
		//}
	}
	else{
		Util::info(Config::AUTH_MESSAGE);
	}
}
//Altera��o ou inclus�o de um registro
if(isset($_GET['db']) && isset($_GET['form'])){
	$ds_forma_pagamento="'".$_POST['ds_forma_pagamento']."'";
	$fl_ativo = $_POST['fl_ativo'];
	if (empty($fl_ativo)){
		$fl_ativo= "'N'";
	}else{
		$fl_ativo= "'".$fl_ativo."'";
	}
	$nm_usuario = "'".strtoupper($user['nm_login'])."'";

	if($_GET['db'] == 1 && $_GET['form'] == 0){

		$groupPr = $_POST['groupPr'];
		$sqlRow = "SELECT nextval('tethys.tb_forma_pagamento_ci_forma_pagamento_seq') as ci_frm_pag";
		$ciRow = Connection::query($sqlRow)->fetch();
		$ci_frm_pag = $ciRow['ci_frm_pag'];

		$sql = "do\n$$\nbegin\n";
		$sql .= 'insert into tethys.tb_forma_pagamento(ci_forma_pagamento,ds_forma_pagamento, dt_cadastro,usr_cadastro,fl_ativo)
		values ('.$ci_frm_pag.',upper('.$ds_forma_pagamento.'),now(),'.$nm_usuario.','.$fl_ativo.');';

		for($i=0;$i<count($groupPr);$i++){
			$valores = explode('$',$groupPr[$i]);
			$sql .= "insert into tethys.tb_prazo_pagamento(cd_forma_pagamento ,nr_dias_prazo ,nr_percentual_prazo )
			values($ci_frm_pag ,$valores[0],$valores[1]);";
		}
		$sql.=" end;\n$$";

	}elseif($_GET['db'] == 1 && $_GET['form'] > 0){

		$groupPr = $_POST['groupPr'];

		$sql = "do\n$$\nbegin\n";
		$sql .=" delete from tethys.tb_prazo_pagamento where cd_forma_pagamento=".$_GET['form'].";";
		$sql .=" update $table set ds_forma_pagamento=$ds_forma_pagamento, fl_ativo=$fl_ativo where $tablepk=".$_GET['form'].";";

		for($i=0;$i<count($groupPr);$i++){
			$valores = explode('$',$groupPr[$i]);
			$sql .= "insert into tethys.tb_prazo_pagamento(cd_forma_pagamento ,nr_dias_prazo ,nr_percentual_prazo )
			values(".$_GET['form'].",$valores[0],$valores[1]);";
		}

		$sql.=" end;\n$$";
	}

	//echo $sql;
	//die;
	if(execute($sql)){
		Controller::setInfo('Forma de Pagamento', 'Salva com sucesso!', 'success', 'info-circle', 3500);
		Controller::redirect(Util::setLink(array('form=null', 'db=null')));
	}
	else{
		Controller::setInfo('Forma de Pagamento', 'Por favor contate o administrador.', 'danger', '', 3500);
	}
}
//Mudan�a do formul�rio para adi��o ou altera��o de registro
if(isset($_GET['form'])){
	if($_GET['form'] == 0){
		$btFormLabel = 'Adicionar';
	}
	else{
		$btFormLabel = 'Salvar';
		$rowEdit =  query("select * from $tableEdit where $tablepk = ".$_GET['form'])->fetch();
		$query = query("select * from tethys.tb_prazo_pagamento where cd_forma_pagamento = ".$_GET['form']);
	}
	$form = true;
}
//Consulta no banco e mec�nica de pagina��o
if(isset($_POST['search1']) || !$form){
	if(isset($_POST['search1'])){
		$term = addslashes($_POST['search1']);
		$where =  " where ds_forma_pagamento ilike '%{$term}%'   ";
	}
	else{
		$where =" where 1=1 ";
	}
	$sql=" select * from $table $where order by $tablepk asc limit {$limitPagina} offset ".(($p - 1) * $limitPagina);
	$sqlc=" select count(*) as num from $table $where ";
	$query = query($sql);
	$rowNum = query($sqlc)->fetch();
	$registros = $rowNum['num'];
	$paginacao = Util::pagination($registros, 4);
}?>

<h3>
	<i class="glyphicon glyphicon-user"></i> Forma de Pagamento -
	<?php echo (!isset($_GET['form']) ? 'Pesquisa' : (@$_GET['form'] > 0 ? 'Edição' : 'Cadastro')); ?>
</h3>
	<?php if(!isset($_GET['form'])){ ?>
<a href="<?php echo Util::setLink(array('form=0')); ?>"
	class="command-page"><span class="fa fa-plus-square"></span> Novo</a>
	<?php } else{ ?>
<a href="#" class="command-page"
	onclick="window.location='?page=cadastros/documentos';"><span
	class="fa fa-reply"></span> Voltar</a>
	<?php } ?>

<div class="panel panel-default">
	<div class="panel-body">
		<div id="alerts"></div>
		<?php if(!isset($_GET['form'])){ ?>
		<form action="<?php echo Util::setLink(array('p=null')); ?>"
			method="post" class="form">
			<div class="row">
				<div class="col-md-8">
					<div class="form-group">
						<label class="control-label">Forma de Pagamento</label> <input
							type="text" name="search1" id="search1"
							value="<?php echo @$_POST['search1']; ?>" class="form-control" />
					</div>
				</div>
				<div class="col-md-2">
					<div class="form-group">
						<button id="btSearch" class="btn btn-default btn-adjust">
							<span class="fa fa-search"></span> Consultar
						</button>
					</div>
				</div>
			</div>
		</form>
		<!-- LISTAGEM DOS REGISTROS -->
		<form method="post" id="formSearch">
			<div class="table-responsive">
				<table
					class="table table-striped table-bordered table-hover table-condensed">
					<thead>
						<tr class="ui-widget-header">
							<th width="25" class="check"><input type="checkbox"
								id="btCheckAll" /></th>
							<th>ID</th>
							<th>Forma de Pagamento</th>
							<th></th>
						</tr>
					</thead>
					<tbody>
					<?php
					$count = 0;
					while($row = $query->fetch()){
						echo '<tr>
						            	<td class="check"><input type="checkbox" class="btCheck" name="checkdel[]" value="'.$row[$tablepk].'"/></td>
						                <td>'.$row['ci_forma_pagamento'].'</td>
						                <td>'.$row['ds_forma_pagamento'].'</td>
						                <td width="30" align="center">
	 					                	<button type="button" onclick="window.location=\''.Util::setLink(array('form='.$row[$tablepk], 'del=null')).'\';" class="btn btn-default btn-xs" title="Editar" data-toggle="tooltip">
										    	<span class="fa fa-pencil"></span>
										    </button>
						                </td>
					           		</tr>';
						$count++;
					}
					?>
					</tbody>
				</table>
			</div>
		</form>
		<!-- FIM FORMULÁRIO PESQUISA -->
		<button id="btDel" class="btn btn-default"
			title="Excluir selecionados" data-toggle="modal"
			data-target="#modalExcluir">
			<span class="fa fa-trash"></span> Excluir
		</button>
		<?php echo $paginacao; ?>
		<?php } else {?>
		<!-- INICIO FORMULÁRIO CADASTRO -->
		<form action="<?php echo Util::setLink(array('db=1')) ?>" class="form"
			method="post" id="formInsertEdit" onsubmit="return test();">
			<fieldset>
				<legend>
					<b>DADOS GERAIS</b>
				</legend>
				<div class="row" id="cadastro_2">
					<div class="col-md-10">
						<div class="form-group">
							<div class="col-md-10">
								<label class="control-label">Forma de Pagamento:<span
									class="text-danger">*</span> </label> <input type="text"
									id="ds_forma_pagamento" name="ds_forma_pagamento"
									value="<?php echo trim(@$rowEdit['ds_forma_pagamento']); ?>"
									class="form-control" size="30" />
							</div>
						</div>
					</div>
				</div>
				<div class="col-md-10">
					<div class="form-group">
						<div class="col-md-10">
							<label class="control-label">Prazo:<span class="text-danger">*</span>
							</label> <input type="text" id="nr_prazo" name="nr_prazo"
								class="form-control" size="30" maxlength="3" />
						</div>
					</div>
				</div>
				<div class="col-md-10">
					<div class="form-group">
						<div class="col-md-10">
							<label class="control-label">Parcelas:<span class="text-danger">*</span>
							</label> <input type="text" id="nr_percentual"
								name="nr_percentual" class="form-control" size="30"
								maxlength="5" /> <a href="javascript:void(0);" id="add_itens"><img
								src="assets/imgs/add.png"> </a>
						</div>
					</div>
				</div>

				<select multiple id="groupPr" name="groupPr[]"
					class="text ui-widget-content ui-corner-all" size="5"
					style="width: 486px;">
					<?php
					if($_GET['form'] != 0){
						while($rowEditing = $query->fetch()){
							echo "<option value=".$rowEditing['nr_dias_prazo']."$".$rowEditing['nr_percentual_prazo'].">Prazo:".$rowEditing['nr_dias_prazo']." Parcelas:".$rowEditing['nr_percentual_prazo']."</option>";
						}
					}
					?>
				</select>
				<div class="col-md-10">
					<div class="form-group">
						<div class="col-md-10">
							<label class="control-label">Ativo:<span class="text-danger">*</span>
							</label> <input type="checkbox" id="fl_ativo" name="fl_ativo"
								value="S" class="btCheck" size="30"
								<?php if(@$rowEdit['fl_ativo'] == 'S'){echo "checked='checked'";} ?> />
						</div>
					</div>
				</div>
			</fieldset>
			<br clear="all">
			<button id="btInsertEdit" class="btn btn-default" type="submit">
				<span class="fa fa-floppy-o"></span> Salvar
			</button>
		</form>
		<!-- FIM FORMULÁRIO CADASTRO-->
		<?php } ?>
	</div>
</div>

<script type="text/javascript">
$(function(){
	$("#ds_forma_pagamento").keyup(function(){
		$(this).val($(this).val().toUpperCase());
	    var varString = $(this).val();
	    var stringAcentos = ('����������������������������');
	    var stringSemAcento = ('aaeouaoaeioucuAAEOUAOAEIOUCU');

	    var i = new Number();
	    var j = new Number();
	    var cString = new String();
	    var varRes = '';

	    for (i = 0; i < varString.length; i++) {
	        cString = varString.substring(i, i + 1);
	        for (j = 0; j < stringAcentos.length; j++) {
	            if (stringAcentos.substring(j, j + 1) == cString){
	                cString = stringSemAcento.substring(j, j + 1);
	            }
	        }
	        varRes += cString;        
	    }
	    varRes = varRes.replace( /\s/g, '' );
	});
	$("#add_itens").click(function(){
	    var nr_prazo = $("#nr_prazo").val();
	    var nr_percentual = $("#nr_percentual").val();
	    if(nr_prazo && nr_percentual){
		    var valida = true;
	        $('#groupPr option').each(function(){
	            if( $(this).val().substring(0,$(this).val().indexOf("$")) == nr_prazo){
	                //console.log("pesquisar => OK!");
	                valida = false;
	                notice('Aviso', 'Prazo já foi adicionado.', 'alert');
	                $("#nr_prazo").val('');	  
	                $("#nr_percentual").val('');              		            	
	            }
	        });
	        
	        if(valida){		      	
	        		$('#groupPr').append('<option value="'+nr_prazo+'$'+nr_percentual+'">Prazo:'+nr_prazo+' Parcelas:'+nr_percentual+'</option>');
	        		$("#nr_prazo").val('');
	        		$("#nr_percentual").val('');
        	}
	    }else{
	        notice('Aviso', 'Por favor, verifique o preenchimento do Prazo e do Percentual.', 'info');
	    }
	});

	$('#groupPr option').dblclick(function() {
		 $(this).remove();
	 });
	
	$("#btnRemover").button({
	    icons: {
	    	primary: "ui-icon-trash"
	    }
    }).click(function(){    	
        var diminuir = parseInt($('#groupPr option:selected').val().substring($('#groupPr option:selected').val().indexOf("$")+1,$('#groupPr option:selected').val().length));
        percent = parseInt($("#percent_atual").val())-diminuir;
        $("#percent_atual").val(percent);
    	$('#groupPr option:selected').remove();
    });

    function notice(title, msg, type){
	$.gritter.add({
		title: title,
		text: msg,
		image: 'assets/css/gritter/growl_'+type+'.png'			
	});	}

	$("#btInsertEdit").click(function(){
		$('#groupPr option').each(function(){
            $(this).prop("selected", true);
        });
	});		
	
});

</script>



